<template>
  <div ref="chartRef" :style="{ width: width, height: height }"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, markRaw } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  options: {
    type: Object,
    required: true,
    default: () => ({})
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '400px'
  },
  theme: {
    type: String,
    default: ''
  }
});

const chartRef = ref(null);
const chartInstance = ref(null);

// Initialize chart
const initChart = () => {
  if (chartRef.value) {
    // Dispose existing instance if any
    if (chartInstance.value) {
      chartInstance.value.dispose();
    }
    
    // Create new instance
    chartInstance.value = markRaw(echarts.init(chartRef.value, props.theme));
    chartInstance.value.setOption(props.options);
    
    // Add resize listener
    window.addEventListener('resize', handleResize);
  }
};

// Handle resize
const handleResize = () => {
  chartInstance.value?.resize();
};

// Watch for options changes
watch(() => props.options, (newOptions) => {
  chartInstance.value?.setOption(newOptions, true); // true = not merge, replace
}, { deep: true });

onMounted(() => {
  initChart();
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  chartInstance.value?.dispose();
});

// Expose resize method
defineExpose({
  resize: handleResize,
  getInstance: () => chartInstance.value
});
</script>

<style scoped>
div {
  overflow: hidden;
}
</style>
